#include "csapp.h"
void echo(int clientfd,char *clientname){
	int serverport=13345;
	int serverfd,n;
	rio_t rio1,rio2;
	char buf[MAXLINE];
	char send[MAXLINE];
	Rio_readinitb(&rio1,clientfd);
	Rio_readinitb(&rio2,serverfd);
	serverfd = open_clientfd(clientname,serverport);
	while( (n=Rio_readlineb(&rio1,buf,MAXLINE))!=0 ){
		Rio_writen(clientfd,buf,n);
		printf("%s",buf);
		Rio_writen(serverfd,buf, n );
	}
	Close(serverfd);
	return;
}
int main(int argc,char **argv){
	int listenfd,clientfd,serverfd;
	char clientname[MAXLINE],clientport[MAXLINE];
	socklen_t len;
	struct sockaddr_storage clientaddr;
	if(argc!=2){
		fprintf(stderr,"usage:%s <port>",argv[1]);
		exit(1);
	}
	listenfd = open_listenfd( atoi(argv[1]) );
	while(1){
		len = sizeof( struct sockaddr_storage );
		clientfd = Accept(listenfd,(SA *)&clientaddr,&len);
		getnameinfo((SA *)&clientaddr,len,clientname,MAXLINE,clientport,MAXLINE,0);
		printf("Accepted Connection from (%s,%s)\n",clientname,clientport);
		echo(clientfd,clientname);
		Close(clientfd);
	}
	exit(0);
}
